<template>
  <el-dialog
    v-model="visible"
    :title="productId ? '编辑商品' : '新增商品'"
    width="800px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
    >
      <el-form-item label="商品名称" prop="productName">
        <el-input v-model="form.productName" placeholder="请输入商品名称" />
      </el-form-item>

      <el-form-item label="商品分类" prop="categoryId">
        <el-select
          v-model="form.categoryId"
          placeholder="请选择分类"
          style="width: 100%"
        >
          <el-option
            v-for="cat in categories"
            :key="cat.id"
            :label="cat.categoryName"
            :value="cat.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="商品编码" prop="productCode">
        <el-input v-model="form.productCode" placeholder="请输入商品编码（可选）" />
      </el-form-item>

      <el-form-item label="商品价格" prop="price">
        <el-input-number
          v-model="form.price"
          :min="0.01"
          :precision="2"
          :step="0.01"
          style="width: 100%"
        />
      </el-form-item>

      <el-form-item label="原价">
        <el-input-number
          v-model="form.originalPrice"
          :min="0.01"
          :precision="2"
          :step="0.01"
          style="width: 100%"
        />
      </el-form-item>

      <el-form-item label="库存数量" prop="stockQuantity">
        <el-input-number
          v-model="form.stockQuantity"
          :min="0"
          :step="1"
          style="width: 100%"
        />
      </el-form-item>

      <el-form-item label="最低库存">
        <el-input-number
          v-model="form.minStock"
          :min="0"
          :step="1"
          style="width: 100%"
        />
      </el-form-item>

      <el-form-item label="主图片">
        <div class="upload-container">
          <el-upload
            class="image-uploader"
            :action="uploadUrl"
            :show-file-list="false"
            :before-upload="beforeMainImageUpload"
            :http-request="handleMainImageUpload"
            :loading="mainImageUploading"
          >
            <img v-if="form.mainImage" :src="getImageUrl(form.mainImage)" class="uploaded-image" />
            <el-icon v-else class="image-uploader-icon"><Plus /></el-icon>
          </el-upload>
          <div class="upload-tip">
            <span>支持jpg、png、gif格式，大小不超过5MB</span>
            <el-button v-if="form.mainImage" link type="danger" size="small" @click="form.mainImage = ''">
              删除图片
            </el-button>
          </div>
        </div>
      </el-form-item>

      <el-form-item label="商品图片">
        <div class="upload-container">
          <el-upload
            class="images-uploader"
            :action="uploadUrl"
            list-type="picture-card"
            :file-list="imageFileList"
            :before-upload="beforeImagesUpload"
            :http-request="handleImagesUpload"
            :on-remove="handleImageRemove"
            :limit="10"
            multiple
          >
            <el-icon class="image-uploader-icon"><Plus /></el-icon>
          </el-upload>
          <div class="upload-tip">
            <span>最多上传10张图片，支持jpg、png、gif格式，每张大小不超过5MB</span>
          </div>
        </div>
      </el-form-item>

      <el-form-item label="商品描述">
        <el-input
          v-model="form.description"
          type="textarea"
          :rows="4"
          placeholder="请输入商品详细描述"
        />
      </el-form-item>

      <el-form-item label="上架状态" prop="status">
        <el-radio-group v-model="form.status">
          <el-radio :label="1">上架</el-radio>
          <el-radio :label="0">下架</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="推荐商品" prop="isFeatured">
        <el-radio-group v-model="form.isFeatured">
          <el-radio :label="1">是</el-radio>
          <el-radio :label="0">否</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" :loading="submitting" @click="handleSubmit">
        确定
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { getCategoryList } from '@/api/category'
import { getProductDetail, createProduct, updateProduct, uploadProductImage } from '@/api/product'
import { getImageUrl, extractRelativePath } from '@/utils/image'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  productId: {
    type: Number,
    default: null
  }
})

const emit = defineEmits(['update:modelValue', 'success'])

const visible = ref(false)
const submitting = ref(false)
const formRef = ref(null)
const categories = ref([])
const mainImageUploading = ref(false)
const imagesUploading = ref(false)
const imageFileList = ref([])
const uploadUrl = import.meta.env.VITE_API_BASE_URL + '/products/upload-image'

const form = reactive({
  productName: '',
  categoryId: null,
  productCode: '',
  price: 0.01,
  originalPrice: null,
  stockQuantity: 0,
  minStock: 0,
  mainImage: '',
  images: '',
  description: '',
  status: 1,
  isFeatured: 0
})

const rules = {
  productName: [
    { required: true, message: '请输入商品名称', trigger: 'blur' }
  ],
  categoryId: [
    { required: true, message: '请选择商品分类', trigger: 'change' }
  ],
  price: [
    { required: true, message: '请输入商品价格', trigger: 'blur' },
    { type: 'number', min: 0.01, message: '价格必须大于0', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择上架状态', trigger: 'change' }
  ]
}

// 加载分类列表
const loadCategories = async () => {
  try {
    const res = await getCategoryList()
    if (res.code === 200 && res.data) {
      categories.value = res.data
    }
  } catch (error) {
    console.error('加载分类列表失败:', error)
  }
}

// 加载商品详情
const loadProductDetail = async () => {
  if (!props.productId) {
    resetForm()
    return
  }

  try {
    const res = await getProductDetail(props.productId)
    if (res.code === 200 && res.data) {
      Object.assign(form, {
        productName: res.data.productName || '',
        categoryId: res.data.categoryId || null,
        productCode: res.data.productCode || '',
        price: res.data.price || 0.01,
        originalPrice: res.data.originalPrice || null,
        stockQuantity: res.data.stockQuantity || 0,
        minStock: res.data.minStock || 0,
        mainImage: res.data.mainImage || '',
        images: res.data.imageList ? res.data.imageList.join(',') : '',
        description: res.data.description || '',
        status: res.data.status || 1,
        isFeatured: res.data.isFeatured || 0
      })
      
      // 设置商品图片列表
      if (res.data.imageList && res.data.imageList.length > 0) {
        imageFileList.value = res.data.imageList.map((url, index) => ({
          name: `image-${index}`,
          url: getImageUrl(url)
        }))
      } else {
        imageFileList.value = []
      }
    }
  } catch (error) {
    console.error('加载商品详情失败:', error)
    ElMessage.error('加载商品详情失败')
  }
}

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    submitting.value = true

    // 从图片列表中提取URL
    const imageUrls = imageFileList.value.map(item => {
      // 如果有response，说明是新上传的
      if (item.response) {
        return item.response
      }
      // 否则从url中提取相对路径
      return extractRelativePath(item.url || '')
    }).filter(url => url)

    const productData = {
      ...form,
      images: imageUrls.length > 0 ? imageUrls : null
    }

    const res = props.productId
      ? await updateProduct(props.productId, productData)
      : await createProduct(productData)

    if (res.code === 200) {
      ElMessage.success(props.productId ? '更新成功' : '创建成功')
      emit('success')
      handleClose()
    } else {
      ElMessage.error(res.message || '操作失败')
    }
  } catch (error) {
    if (error !== false) {
      console.error('提交失败:', error)
    }
  } finally {
    submitting.value = false
  }
}

// getImageUrl 已从 @/utils/image 导入，无需重复定义

// 主图上传前检查
const beforeMainImageUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt5M = file.size / 1024 / 1024 < 5

  if (!isImage) {
    ElMessage.error('只能上传图片文件！')
    return false
  }
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过 5MB！')
    return false
  }
  return true
}

// 主图上传处理
const handleMainImageUpload = async ({ file }) => {
  mainImageUploading.value = true
  try {
    const res = await uploadProductImage(file)
    if (res.code === 200 && res.data) {
      form.mainImage = res.data
      ElMessage.success('上传成功')
    } else {
      ElMessage.error(res.message || '上传失败')
    }
  } catch (error) {
    console.error('上传失败:', error)
    ElMessage.error('上传失败')
  } finally {
    mainImageUploading.value = false
  }
}

// 商品图片上传前检查
const beforeImagesUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt5M = file.size / 1024 / 1024 < 5

  if (!isImage) {
    ElMessage.error('只能上传图片文件！')
    return false
  }
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过 5MB！')
    return false
  }
  return true
}

// 商品图片上传处理
const handleImagesUpload = async ({ file }) => {
  imagesUploading.value = true
  try {
    const res = await uploadProductImage(file)
    if (res.code === 200 && res.data) {
      // 添加到图片列表
      imageFileList.value.push({
        name: file.name,
        url: getImageUrl(res.data),
        response: res.data
      })
      ElMessage.success('上传成功')
    } else {
      ElMessage.error(res.message || '上传失败')
    }
  } catch (error) {
    console.error('上传失败:', error)
    ElMessage.error('上传失败')
  } finally {
    imagesUploading.value = false
  }
}

// 移除图片
const handleImageRemove = (file) => {
  const index = imageFileList.value.findIndex(item => item.uid === file.uid)
  if (index > -1) {
    imageFileList.value.splice(index, 1)
  }
}

// 重置表单
const resetForm = () => {
  Object.assign(form, {
    productName: '',
    categoryId: null,
    productCode: '',
    price: 0.01,
    originalPrice: null,
    stockQuantity: 0,
    minStock: 0,
    mainImage: '',
    images: '',
    description: '',
    status: 1,
    isFeatured: 0
  })
  imageFileList.value = []
  formRef.value?.clearValidate()
}

// 关闭对话框
const handleClose = () => {
  visible.value = false
  resetForm()
  emit('update:modelValue', false)
}

// 监听visible变化
watch(() => props.modelValue, (val) => {
  visible.value = val
  if (val) {
    loadCategories()
    loadProductDetail()
  }
})

// 监听visible变化同步到props
watch(visible, (val) => {
  emit('update:modelValue', val)
})
</script>

<style lang="scss" scoped>
.upload-container {
  width: 100%;
  
  .upload-tip {
    margin-top: 8px;
    font-size: 12px;
    color: #909399;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}

.image-uploader {
  :deep(.el-upload) {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: all 0.3s;
    width: 148px;
    height: 148px;
    display: flex;
    align-items: center;
    justify-content: center;

    &:hover {
      border-color: #409eff;
    }
  }

  .uploaded-image {
    width: 148px;
    height: 148px;
    display: block;
    object-fit: cover;
  }

  .image-uploader-icon {
    font-size: 28px;
    color: #8c939d;
  }
}

.images-uploader {
  :deep(.el-upload--picture-card) {
    width: 148px;
    height: 148px;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  :deep(.el-upload-list__item) {
    width: 148px;
    height: 148px;
  }

  .image-uploader-icon {
    font-size: 28px;
    color: #8c939d;
  }
}
</style>
